<template>
  <BaseMainSlot>
    <template v-slot:searchbox>
      <el-collapse v-model="activeName" accordion @change="handleChange">
        <el-collapse-item name="1">
          <template slot="title">
            <div class="select-btns search-btns" @click.stop="changeSelect()">
              <i class="el-icon-circle-check"></i>
              <p v-if="activeName === '1'">收起筛选</p>
              <p v-if="activeName === ''">展开筛选</p>
            </div>
          </template>
          <div class="search-btn search-btns" @click.stop="queryPageList()">
            <i class="el-icon-circle-check"></i>
            <p>查询</p>
          </div>
          <div class="select-box-content">
            <div class="select-box-content-name">生成溯源码</div>
            <el-select filterable clearable v-model="searchForm.traceSourceCodeConfigId" placeholder="请选择">
              <el-option v-for="item in QRCodeList" :key="item.traceSourceCodeConfigId" :label="item.batchName"
                :value="item.traceSourceCodeConfigId" :disabled="item.disabled">
              </el-option>
            </el-select>
          </div>
        </el-collapse-item>
      </el-collapse>
    </template>
    <template v-slot:btnsBar>
      <ActionBar :add-active="addActive" :del-active="delActive" :page-no="163" @add="add" @del="del" />
    </template>
    <template v-slot:content>
      <el-table ref="tableData" v-loading="loading" highlight-current-row :data="tableData" stripe border
        height="calc(100% - 50px)" :row-key="row => {
        return row.traceSourceCodeConfigId;
      }
        " @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" :reserve-selection="true" :selectable="selectable" />
        <el-table-column type="index" label="序号" width="50">
          <template slot-scope="scoped">{{ scoped.row.traceSourceCodeConfigId ? scoped.$index + 1 : '' }}</template>
        </el-table-column>
        <el-table-column prop="batchName" label="码单号" />
        <el-table-column prop="rangeStr" label="溯源可见范围" />
        <el-table-column prop="createTime" label="配置时间" />
        <el-table-column prop="traceSourceCode" label="溯源码">
          <template slot-scope="scoped">
            <span style="color: #007fed; cursor: pointer;" @click="getTraceSourceCode(scoped.row)">{{
        scoped.row.traceSourceCode
      }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-if="scoped.row.traceSourceCodeConfigId" slot-scope="scoped">
            <div class="table-btns-box">
              <div class="table-btns edit-btns" @click="edit(scoped.row)" v-if="judgePermission(163, 'edit')">
                <p>修改</p>
              </div>
              <div class="table-btns edit-btns" @click="downLoadExcel(scoped.row)">
                <p>导出溯源码</p>
              </div>
              <div class="table-btns edit-btns" @click="delOne(scoped.row)">
                <p>删除</p>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <Pagination :page-size="pageSize" :current-page="currentPage" :total-size="totalSize"
        @changeCurrentPage="changeCurrentPage" />
      <AddEditDialog ref="addEditDialog" :batchList="batchList" :checkInfoList="checkInfoList"
        :now-chance-stau="nowChanceStau" :title-text="titleText" :edit-object="editObject"
        :show.sync="showAddEditDialog" @closeDialog="closeDialog" @cancelDialog="cancel" />
      <el-dialog title="二维码预览" :visible.sync="dialogVisible" :before-close="handleClose">
        <div style="width: 300px;height: 300px;" class="QrcodeImg">
          <Qrcode v-if="showCode" @getImgUrl="getImgUrl"
            :apkUrl="`http://fishery.ssagroup.cn:8080/h5/#/?traceSourceFlag=true&traceSourceCode=${traceSourceCode}`">
          </Qrcode>
        </div>
        <div style="margin-top: 10px;text-align: center;">溯源码：{{ traceSourceCode }}</div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
        </span>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import BaseMainSlot from "@/components/BaseMainSlot/kong-new2.vue";
import AddEditDialog from "./components/add-edit-dialog.vue";
import { mymixin } from "@/utils/mixin";
import { mapGetters } from "vuex";
import Qrcode from "@/components/qrcode";
import QRCode from 'qrcode'
import table2excel from 'js-table2excel'

import BatchMangeApi from "@/api/batch-mange";
import QRCodeMsgApi from "@/api/traceability/basicsInfo/QRCodeMsg";
import FishVarietyApi from "@/api/basic-info-manage/fishVariety";
import FishPondApi from "@/api/basic-info-manage/fishPond";
export default {
  name: "BatchCreate",
  components: { ActionBar, Pagination, BaseMainSlot, AddEditDialog, Qrcode },
  mixins: [mymixin],
  data() {
    return {
      traceSourceCode: '',
      dialogVisible: false,
      searchForm: {},
      currentPage: 1,
      closePondDateTimeList: [],
      mnecode: "", //批次编号
      productionBatchCode: "", //码单号
      fishPondId: "", //养殖鱼塘ID
      fishVarietyId: "", //养殖品种ID
      buildDateTime: "", //批次创建时间
      checkedIdList: [],
      fishPondList: [], //全部鱼塘
      FishVarietyData: [], //全部品种
      showAddEditDialog: false,
      routerParams: {},
      batchList: [],
      QRCodeList: [],
      batchObj: {},
      tableData: [],
      QRImgUrl: '',
      showCode: true,
      checkInfoList: [{
        value: '1',
        label: '种苗信息'
      }, {
        value: '2',
        label: '农资信息'
      }, {
        value: '3',
        label: '出鱼信息'
      },
      {
        value: '4',
        label: '转塘记录'
      }, {
        value: '5',
        label: '生长环境数据'
      }, {
        value: '6',
        label: '作业数据'
      }, {
        value: '7',
        label: '农资投入信息'
      }, {
        value: '8',
        label: '防治数据'
      }, {
        value: '9',
        label: '治疗数据'
      }, {
        value: '10',
        label: '疾病统计'
      },
      {
        value: '11',
        label: '检验报告'
      }],
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {},
  created() {
    this.routerParams = this.$route.params ? this.$route.params : {}
    console.log(this.routerParams, '路由参数')
  },
  async mounted() {
    await this.queryBatch();
    this.queryByCondition()
    this.queryPageList()
  },
  methods: {
    setTime() {
      this.showCode = false
      setTimeout(() => {
        this.showCode = true
      }, 100)
    },
    handleClose(done) {
      done();
    },
    getImgUrl(url) {
      console.log(url)
    },
    async getQRcode(url) {
      let opts = {
        errorCorrectionLevel: "L",//容错级别
        type: "image/png",//生成的二维码类型
        quality: 0.5,//二维码质量
        margin: 2,//二维码留白边距
        width: 130,//宽
        height: 130,//高
        color: {
          dark: "#666666",//前景色
          light: "#fff"//背景色
        }
      };
      //this.QRlink 生成的二维码地址url
      await QRCode.toDataURL(url, opts).then(res => {
        this.QRImgUrl = res
      })
    },
    getTraceSourceCode(row) {
      console.log(row)
      return
      this.traceSourceCode = row.traceSourceCode;
      this.dialogVisible = true;
      this.setTime();
    },
    dataURLtoBlob(base64Data) {
      let tmp = base64Data.split(',');
      if (tmp.length === 2) { // 如果base64包含头部的话，去掉base64的头
        tmp.shift()
      }
      var bytes = window.atob(tmp) // 转换为byte;
      // 处理异常,将ascii码小于0的转换为大于0
      var ab = new ArrayBuffer(bytes.length);
      var ia = new Uint8Array(ab);
      for (var i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i)
      }
      return new window.Blob([ab], { type: 'application/octet-stream' })
    },
    async downLoadExcel(row) {
      let url = `http://fishery.ssagroup.cn:8080/h5/#/?traceSourceFlag=true&traceSourceCode=${row.traceSourceCode}`
      await this.getQRcode(url)
      const column = [
        { title: '码单号', key: 'batchName', type: 'text' },
        { title: '溯源编码', key: 'traceSourceCode', type: 'text' },
        { title: '配置时间', key: 'timestamp', type: 'text' },
        { title: '溯源二维码管理', key: 'qrCodeImg', type: 'image', width: 200, height: 200 },
      ]
      console.log(this.QRImgUrl)
      const data = [
        {
          batchName: row.batchName,
          traceSourceCode: '编码：' + row.traceSourceCode,
          timestamp: row.timestamp,
          qrCodeImg: this.QRImgUrl,
        },
      ]
      const excelName = '溯源码详情'                //文件名称
      table2excel(column, data, excelName)    //生成Excel表格，自动下载
    },
    queryPageList() {
      let params = {
        page: this.currentPage,
        size: 10,
        entity: {
          ...this.searchForm,
          homeBaseId: sessionStorage.getItem('homeBaseId'),
        }
      }
      let checkInfoObj = {}
      this.checkInfoList.forEach(data => {
        checkInfoObj[data.value] = data.label
      })
      QRCodeMsgApi.queryPageByCondition(params).then(res => {
        res.data.content.forEach(data => {
          if (data.range) {
            let str = ''
            data.range.split(',').forEach(id => {
              str += checkInfoObj[id] + '/'
            })
            data['rangeStr'] = str
          } else {
            data['rangeStr'] = ''
          }
          this.tableData = res.data.content;
          this.totalSize = res.data.totalElements;
          this.addblankmet();
          this.resetActionBar();
        })
      })
    },
    isJSON(str) {
      if (typeof str == 'string') {
        try {
          var obj = JSON.parse(str);
          // 等于这个条件说明就是JSON字符串 会返回true
          if (typeof obj == 'object' && obj) {
            return true;
          } else {
            //不是就返回false
            return false;
          }
        } catch (e) {
          return false;
        }
      }
      return false;
    },
    queryByCondition() {
      QRCodeMsgApi.queryByCondition({
        homeBaseId: sessionStorage.getItem('homeBaseId')
      }).then(res => {
        this.QRCodeList = res.data
      })
    },
    async queryBatch() {
      await BatchMangeApi.queryByCondition({ homeBaseId: sessionStorage.getItem('homeBaseId') }).then(res => {
        if (res && res.data) {
          this.batchList = res.data
          res.data.forEach(batch => {
            this.batchObj[batch.productionBatchId] = batch.mnecode
          })
          console.log('批次', res)
        } else {
          this.batchList = []
        }
      })
    },
    //查询可选鱼类品种
    queryFishVariety() {
      FishVarietyApi.queryByCondition().then(res => {
        this.FishVarietyData = res.data;
      });
    },
    //查询可选鱼塘
    queryFishPond() {
      FishPondApi.queryByCondition().then(res => {
        this.fishPondList = res.data;
      });
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.queryPageList();
    },
    selectAll(list) {
      let notvalue = true;
      list.forEach(item => {
        if (!item.productionBatchId) {
          notvalue = false;
        }
      });
      if (notvalue === false) {
        this.$message.warning("不可选择空数据！");
      }
    },
    select(list) {
      let notvalue = true;
      list.forEach(item => {
        if (!item.productionBatchId) {
          notvalue = false;
        }
      });
      if (notvalue === false) {
        this.$message.warning("不可选择空数据！");
      }
    },
    handleSelectionChange(list) {
      this.checkedIdList = [];
      let notvalue = true;
      let emptyList = [];
      this.checkedIdList = list.map(item => {
        if (item.traceSourceCodeConfigId) {
          return item.traceSourceCodeConfigId;
        } else {
          notvalue = false;
          emptyList.push(item);
          return "";
        }
      });
      console.log(notvalue, this.checkedIdList)
      if (notvalue === false) {
        this.toggleNoSelection(emptyList);
        return;
      }
      if (this.checkedIdList.length >= 1) this.delActive = true;
      else this.delActive = false;
    },
    // 表格删除
    delmessage() {
      QRCodeMsgApi.delListById({ idList: this.checkedIdList }).then(res => {
        if (res.success) {
          this.$message.success("删除成功");
          this.queryPageList();
          this.resetActionBar();
        }
      });
    },
    // 单个删除
    delOne(row) {
      this.$confirm("此操作将永久删除该项, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",

      })
        .then(() => {
          QRCodeMsgApi.delById({ id: row.traceSourceCodeConfigId }).then(res => {
            if (res.success === true) {
              this.$message.success("删除成功!");
              this.queryPageList();
              this.resetActionBar();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 添加
    add() {
      this.nowChanceStau = "add";
      this.titleText = "添加";
      this.addActive = false;
      this.delActive = false;
      this.showAddEditDialog = true;
    },
    // 修改
    edit(row) {
      if (row.traceSourceCodeConfigId) {
        this.editObject = JSON.parse(JSON.stringify(row));
        this.nowChanceStau = "edit";
        this.titleText = "修改";
        this.addActive = false;
        this.delActive = false;
        this.showAddEditDialog = true;
      } else {
        this.editObject = {};
      }
    },
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-range-separator {
  color: #333333;
}

.select-box-content-name {
  min-width: 80px;
}

.QrcodeImg {
  margin: 0 auto;

  img {
    width: 100%;
    height: 100%;
  }
}

.select-box-content {
  width: none !important;
}
</style>
